package com.fahai.web.controller;

import com.fahai.common.PageVo;
import com.fahai.utils.DateUtil;
import com.fahai.utils.ExcelExport;
import com.fahai.utils.json.JsonResult;
import com.fahai.web.service.LawyerTxService;
import com.fahai.web.vo.PayFlowQueryVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;


/**
 * Created by sky on 17/5/10.
 * 财务结算管理
 */
@Controller
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequestMapping("/finance")
public class FinanceController extends BaseController {
    static Logger logger = LoggerFactory.getLogger(FinanceController.class);

    @Autowired
    private LawyerTxService lawyerTxService;

    /**
     * 返回账号权限列表数据
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','财务结算管理-0','财务结算管理-1')")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String enterSysUserList(Model model) {
        model.addAttribute("selectTab","财务结算管理");
        return "financial_manage";
    }



    /**
     * 查询律师提现列表
     * @param
     * @return
     */
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ADMIN','财务结算管理-0','财务结算管理-1')")
    @RequestMapping(value="/getLawyertxList",method = RequestMethod.GET)
    public JsonResult getLawyerAll(PageVo pageVo, String lawyername, String lawyerphone, String beginTime, String endTime, Integer txStats,Integer orderBy){

        beginTime=DateUtil.getStartTimeStr(beginTime);
        endTime=DateUtil.getEndTimeStr(endTime);

        pageVo=lawyerTxService.findLawyerTXList( lawyername,  lawyerphone,  beginTime,  endTime,  txStats,orderBy,pageVo);

        return ok("查询律师提现记录列表",pageVo);
    }



    /**
     * 查询用户充值记录
     * @param
     * @return
     */
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ADMIN','财务结算管理-0','财务结算管理-1')")
    @RequestMapping(value="/getPayFlownoList",method = RequestMethod.GET)
    public JsonResult getPayFlownoAll(PageVo pageVo, String uphone, String beginTime, String endTime, Integer orderPayState,Integer orderBy){

        beginTime=DateUtil.getStartTimeStr(beginTime);
        endTime=DateUtil.getEndTimeStr(endTime);

        pageVo=lawyerTxService.findPayFlownoList(uphone,beginTime,endTime,orderPayState,orderBy,pageVo);

        return ok("查询用户充值记录列表",pageVo);
    }
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ADMIN','财务结算管理-0','财务结算管理-1')")
    @RequestMapping(value="/gettotalmoney",method = RequestMethod.GET)
    public PayFlowQueryVO getTotalMoney(PageVo pageVo, PayFlowQueryVO conditionvo){
       String  beginTime=DateUtil.getStartTimeStr(conditionvo.getBeginTime());
        conditionvo.setBeginTime(beginTime);
       String  endTime=DateUtil.getEndTimeStr(conditionvo.getEndTime());
        conditionvo.setEndTime(endTime);
        PayFlowQueryVO  vo=lawyerTxService.getTotalMoney(conditionvo ,pageVo);
        return vo;
    }




    /**
     * //处理提现记录
     * @param
     * @return
     */
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ADMIN','财务结算管理-0')")
    @RequestMapping(value="/updateLawyerTxHandle",method = RequestMethod.GET)
    public JsonResult updateLawyerTxHandle(@RequestParam Integer txId,@RequestParam String returnNum, @RequestParam String remak){

        lawyerTxService.updateLawyerTxHandle(txId,returnNum,remak);

        return ok("处理完成");
    }




    /**
     * 导出Excel
     * @param
     * @return
     */
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ADMIN','财务结算管理-0','财务结算管理-1')")
    @RequestMapping(value="/excelLaywerWithList",method = RequestMethod.GET)
    public JsonResult excelLaywerWithList(String lawyername, String lawyerphone, String beginTime, String endTime, Integer txStats,Integer orderBy,HttpServletResponse response){


        beginTime=DateUtil.getStartTimeStr(beginTime);
        endTime=DateUtil.getEndTimeStr(endTime);

        List<HashMap<String,Object>> getData=lawyerTxService.excelLawyerWithList(lawyername,  lawyerphone,  beginTime,  endTime,  txStats,orderBy);

        List dataset = new ArrayList();

        for (HashMap<String,Object> md:getData) {

            String txsqTime=DateUtil.TimeStampToString(Timestamp.valueOf(md.get("txsq_time").toString()),"yyyy-MM-dd HH:mm:ss");

            String updateTime=DateUtil.TimeStampToString(Timestamp.valueOf(md.get("update_time").toString()),"yyyy-MM-dd HH:mm:ss");

            Integer txMoney=Integer.parseInt(md.get("tx_money").toString());


            BigDecimal txMoneyTemp = new BigDecimal(txMoney);

            BigDecimal b2 = new BigDecimal("100");

            BigDecimal b3 = txMoneyTemp.divide(b2,0,BigDecimal.ROUND_HALF_EVEN);

            Object[] obj = new Object[]{md.get("lawyername"),md.get("lawyer_phone"),txsqTime, b3 ,md.get("tx_name"),md.get("tx_bankcard"),md.get("tx_bank"),md.get("tx_bank_area"),Integer.parseInt(md.get("tx_stats").toString())==0?"待处理":"已处理" ,md.get("return_num"),md.get("remak"),Integer.parseInt(md.get("tx_stats").toString())==0?"":updateTime};
            dataset.add(obj);
        }
        
        

        String[] headers = new String[]{"律师姓名", "手机号", "提现申请时间", "提现金额","持卡人姓名","卡号","银行名称","开户行全称","处理结果","回执结果","备注","处理时间"};

        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + UUID.randomUUID().toString() + ".xls");
            OutputStream os = response.getOutputStream();
            ExcelExport.expExcel("律师提现记录", headers, dataset, os);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return ok("导出成功");
    }




    /**
     * 导出用户充值记录
     * @param
     * @return
     */
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ADMIN','财务结算管理-0','财务结算管理-1')")
    @RequestMapping(value="/excelPayList",method = RequestMethod.GET)
    public JsonResult excelPayList(String uphone, String beginTime, String endTime, Integer orderPayState,Integer orderBy,HttpServletResponse response){

        if(beginTime!=null&&(!"".equals(beginTime))){
            beginTime+=" 00:00:00";
        }


        if(endTime!=null&&(!"".equals(endTime))) {
            endTime+=" 23:59:59";

        }

        List<HashMap<String,Object>> getData=lawyerTxService.excelPayList(uphone,beginTime,endTime,orderPayState,orderBy);



        List dataset = new ArrayList();

        for (HashMap<String,Object> md:getData) {

            String orderTime="";

            String wxTimeStart="";//改成sku

            String wxTimeEnd="";//改成sku

            if(md.get("order_time")!=null&&!"".equals(md.get("order_time").toString())){

                orderTime=DateUtil.TimeStampToString(Timestamp.valueOf(md.get("order_time").toString()),"yyyy-MM-dd HH:mm:ss");
            }

            if(md.get("wx_time_start")!=null&&!"".equals(md.get("sku_star_time").toString())){

                wxTimeStart= DateUtil.strToDateFormat(md.get("sku_star_time").toString());

            }


            if(md.get("sku_end_time")!=null&&!"".equals(md.get("sku_end_time").toString())){

              //  wxTimeEnd=DateUtil.TimeStampToString(Timestamp.valueOf(md.get("wx_time_end").toString()),"yyyy-MM-dd HH:mm:ss");

                   String time=md.get("sku_end_time").toString();

                   Date d=DateUtil.StringToDate(time,"yyyy-MM-dd hh:mm:ss");
                   wxTimeEnd= DateUtil.DateToString(d,"yyyy-MM-dd hh:mm:ss");

            }

            Integer skutoprice=0;

                if(null!=md.get("skutoprice")&&!"".equals(md.get("skutoprice"))){

                    skutoprice=Integer.parseInt(md.get("skutoprice").toString());
                }


            BigDecimal skutopriceTemp = new BigDecimal(skutoprice);

            BigDecimal b2 = new BigDecimal("100");

            BigDecimal skutopriceTemp100 = skutopriceTemp.divide(b2,0,BigDecimal.ROUND_HALF_EVEN);
            Integer skudeprice=0;

            if(null!=md.get("skudeprice")&&!"".equals(md.get("skudeprice"))){
                  skudeprice=Integer.parseInt(md.get("skudeprice").toString());
            }

            BigDecimal skudepriceTemp = new BigDecimal(skudeprice);

            BigDecimal skudepriceTemp100 = skudepriceTemp.divide(b2,0,BigDecimal.ROUND_HALF_EVEN);


            String sku="";

            String sn="";

            Object skusn=md.get("skusn");

            if(skusn!=null&&!"".equals(skusn.toString())){
                System.out.println(skusn);
                String[] sns=skusn.toString().split("-");
                if(null!=sns&&sns.length>0){
                    sku=sns[0];
                    sn=sns[1];
                }
            }


           String paySate=Integer.parseInt(md.get("order_pay_state").toString())==0?"成功":Integer.parseInt(md.get("order_pay_state").toString())==1?"支付中":"失败";



            String payType=Integer.parseInt(md.get("pay_type").toString()) ==1?"支付宝":"微信";

            Object[] obj = new Object[]{md.get("uname"),md.get("userid"),md.get("uphone"),orderTime,wxTimeStart,wxTimeEnd,md.get("sku_type"),md.get("pro_name"),sku,sn,skutopriceTemp100,skudepriceTemp100,md.get("sku_publish"), paySate,skudepriceTemp100, payType};
            dataset.add(obj);
        }


        String[] headers = new String[]{"用户姓名", "用户ID", "手机号", "充值时间","起始效期","终止效期","产品分类","产品名称","产品SN","渠道SN","面值","定价（元）","发行方","充值状态","实付金额(元)","支付方式"};

        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + UUID.randomUUID().toString() + ".xls");
            OutputStream os = response.getOutputStream();
            ExcelExport.expExcel("用户充值记录", headers, dataset, os);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return ok("查询用户充值记录列表");
    }



}
